package com.situ.staff.listener;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

import com.situ.staff.bean.User;

/**
 * 
 * @author: JavaSiegeLoin(Gang)
 * @E-mail: wzg15653@163.com
 * @创建日期: 2021年9月9日 下午4:53:42
 * @ClassName LoginListener
 * @类描述-Description:监听器(解决用户重复登录)
 */
@WebListener
public class LoginListener implements HttpSessionAttributeListener {

	public void attributeAdded(HttpSessionBindingEvent se) {
		// 如果添加的属性是user onlineCount++
		if (se.getName().equals("user")) {
			// 获取application对象
			ServletContext app = se.getSession().getServletContext();
			Integer onlineCount = (Integer) app.getAttribute("onlineCount");
			if (onlineCount == null) {
				onlineCount = 1;
			} else {
				onlineCount++;
			}
			app.setAttribute("onlineCount", onlineCount);
			// 如果当前账号已经登录 需要顶掉
			User user = (User) se.getValue();
			// 验证是否登录
			Map<Integer, HttpSession> loginUserMap = (Map<Integer, HttpSession>) app.getAttribute("loginUserMap");
			if (loginUserMap == null) {
				loginUserMap = new HashMap<Integer, HttpSession>();
			} else {
				// 判断当前用户在Map是否存在
				if (loginUserMap.containsKey(user.getId())) {
					// 是的话 顶掉
					HttpSession session = loginUserMap.get(user.getId());
					session.invalidate();

				}

			}
			// 保存当前账号到application中
			loginUserMap.put(user.getId(), se.getSession());
			app.setAttribute("loginUserMap", loginUserMap);

		}

	}

	public void attributeRemoved(HttpSessionBindingEvent se) {
		// 如果添加的属性是user onlineCount--
		if (se.getName().equals("user")) {
			ServletContext app = se.getSession().getServletContext();
			Integer onlineCount = (Integer) app.getAttribute("onlineCount");
			onlineCount--;
			app.setAttribute("onlineCount", onlineCount);

			// 移除当前session
			User user = (User) se.getValue();

			Map<Integer, HttpSession> loginUserMap = (Map<Integer, HttpSession>) app.getAttribute("loginUserMap");
			loginUserMap.remove(user.getId());

		}

	}

	public void attributeReplaced(HttpSessionBindingEvent se) {

	}

}
